﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using TinyPMS_Jerusalem.Models;
using TinyPMS_Jerusalem.Models.DBModel;
using TinyPMS_Jerusalem.ViewModels;
using TinyPMS_Jerusalem.Models.Validation;

namespace TinyPMS_Jerusalem.Controllers
{

    [HandleError(View="Error")]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        List<SelectListItem> genderList;

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {         
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    if (MembershipService.IsUserApproved(model.UserName))
                    {
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "您的账户还未经过审核，请联系系统管理员");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            if (MembershipService.CanRegister())   //判断当前系统是否允许注册
            {
                ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
                return View();
            }
            else
            {
                throw new Exception("当前系统不允许注册。");
            }
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email,false);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    string encryptedFillInfoLinkString = Models.CommonCode.SHA1Encrypt(model.UserName + "TinyPMS");   //加密链接字符串
                    DBModelDataContext context=new DBModelDataContext();
                    Repository<UserInfo> infoRepository = new Repository<UserInfo>(context);
                    UserInfo info = new UserInfo();   //创建新的UserInfo实例
                    info.Phone = "";   //IMPORTANT:为UserInfo实例填写默认值，防止数据库写入时“值不能为空”异常的发生。
                    info.Name = "";
                    info.Address = "";
                    info.FillInfoLinkString = encryptedFillInfoLinkString;   //写入已加密的链接字符串
                    info.UserName = model.UserName;     //填入当前已注册的用户名
                    infoRepository.Add(info);
                    infoRepository.Save();   //保存更改
                    RouteValueDictionary valueDict = new RouteValueDictionary();
                    valueDict.Add("fillInfoLinkString", encryptedFillInfoLinkString);
                    return RedirectToAction("FillInfo",valueDict);   //Todo:将用户转向填写UserInfo的Action
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        // **************************************
        // URL: /Account/FillInfo
        // **************************************
        public ActionResult FillInfo(string fillInfoLinkString)
        {
            Repository<UserInfo> infoRepository = new Repository<UserInfo>(new DBModelDataContext());
            IEnumerable<UserInfo> infos=infoRepository.GetAll(c => c.FillInfoLinkString == fillInfoLinkString&&c.IsUserInfoFilled==false);
            if (infos.Count()<=0)   //判断对应的用户是否需要填写信息
                throw new ArgumentException("未能找到对应的用户信息");
            MembershipService.CreateViewDataForDropList(out genderList);
            ViewData["Gender"] = genderList;
            return View();
        }

        [HttpPost]
        public ActionResult FillInfo(string fillInfoLinkString, UserInfoModel model)
        {
            if (ModelState.IsValid)
            {
                MembershipService.UpdateUserInfo(model, fillInfoLinkString);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "用户信息未能成功更新，请检查您的输入。");
                MembershipService.CreateViewDataForDropList(out genderList);
                ViewData["Gender"] = genderList;
                return View();
            }
        }

        [Authorize(Roles="Admin")]
        public ActionResult PendingUsers()
        {
            List<PendingUserModel> list = MembershipService.GetPendingUsers();
            return View(list);
        }

        [Authorize(Roles="Admin")]
        public ActionResult ApproveUser(string id)
        {
            Repository<aspnet_Membership> membershipRepository = new Repository<aspnet_Membership>(new DBModelDataContext());
            List<aspnet_Membership> membershipList = membershipRepository.GetAll(c => c.UserId.ToString() == id).ToList();
            if (membershipList.Count <= 0)
                throw new ArgumentException("不存在此用户");
            else
            {
                membershipList.Single().IsApproved = true;
                membershipRepository.Save();
                return RedirectToAction("PendingUsers");
            }
        }

        [Authorize(Roles="Admin")]
        public ActionResult DenyUser(string id)
        {
            Repository<aspnet_Membership> membershipRepository = new Repository<aspnet_Membership>(new DBModelDataContext());
            List<aspnet_Membership> membershipList = membershipRepository.GetAll(c => c.UserId.ToString() == id).ToList();
            if (membershipList.Count <= 0)
                throw new ArgumentException("不存在此用户");
            else
            {
                aspnet_Membership membership=membershipList.Single();
                if(membership.IsApproved==true)
                    throw new Exceptions.PermissionDeniedException("此用户已经被审核通过。如果您希望删除此用户，请使用删除用户功能。");
                else
                {
                    MembershipService.DenyUser(membership.aspnet_Users.UserName,true);
                    return RedirectToAction("PendingUsers");
                }
            }
        }
    }
}
